import { createSlice } from '@reduxjs/toolkit'

const tabSlice = createSlice({
  name: 'tab',
  initialState: {
    isCollapse: false,
    tabList: [
      {
        path: '/',
        name: 'home',
        label: '首页'
      }
    ],
    currentMenu: {}
  },
  reducers: {
    collapseMenu: state => {
      state.isCollapse = !state.isCollapse
    },
    selectMenuList: (state, { payload: val }) => {
      if (val.name !== 'home') {
        state.currentMenu = val;
        // 如果已经存在额tag就不需要添加
        const result = state.tabList.findIndex(item => item.name === val.name)
        result === -1 && state.tabList.push(val)
      } else {
        state.currentMenu = ''
      }
    },
    closeTab: (state, { index }) => {
      state.tabList.splice(index, 1)
    }
  }
})

export const { collapseMenu, selectMenuList, closeTab } = tabSlice.actions
export default tabSlice.reducer